package com.example.bus.google.config;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;


/**
 * @author guoqi
 * // 该例子使用Spring注解@Configuration+@Bean的方式定义了一个事件总线bean，该bean最终的创建虽然使用了Java
 * // 关键字new，但整个bean的生命周期管理都托管给了Spring IoC容器，这是很“Spring”的应用方式，避免了开发人员自己
 * // 负责事件总线对象的生命周期管理
 */
@Configuration
public class EventBusConfig {

    /**
     * 定义事件总线bean
     *
     * @return EventBus
     */
//    @Bean
//    public EventBus eventBus() {
//        return new EventBus();
//    }
    @Bean
    public EventBus eventBus() {
        BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<Runnable>(500);

        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("eventBus-thread-%s").build();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 500, 30, TimeUnit.SECONDS, workQueue, threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
        return new AsyncEventBus(executor);

    }
}
